//使用递归的方式实现数组、对象的深拷贝
import Vue from "vue";
import {Storage} from "./Storage";

function deepClone1(obj) {
    //判断拷贝的要进行深拷贝的是数组还是对象，是数组的话进行数组拷贝，对象的话进行对象拷贝
    const objClone = Array.isArray(obj) ? [] : {};
    //进行深拷贝的不能为空，并且是对象或者是
    if (obj && typeof obj === "object") {
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                if (obj[key] && typeof obj[key] === "object") {
                    objClone[key] = deepClone1(obj[key]);
                } else {
                    objClone[key] = obj[key];
                }
            }
        }
    }
    return objClone;
}


const MERGE_DATA_EVENT_NAME = [];
const PAGE_LIFE_CYCLE = {
    onLoad(data) {
        const vm = this;
        const {isEmpty, isEmptyObject} = this.$util.jude;
        let NavigationBarOptions = !isEmptyObject(this.navigationBarOptions) ? this.navigationBarOptions : {};
        console.warn(data, 'onLoad：页面加载时触发。', {...NavigationBarOptions});
        if (NavigationBarOptions.title) this.$$$setNavigationBarTitle && this.$$$setNavigationBarTitle(NavigationBarOptions);
        for (let key in data) data[key] = NonValue(data[key]);
        if (!isEmpty(data.q)) {
            const query = this.$util.qs.parse(data.q, true)
            data = {...data, ...query}
        } else if (!isEmpty(data.scene)) {
            const query = this.$util.qs.parse(`https://res.tuoluocard.com?${data.scene}`, true)
            data = {...data, ...query}
        }
        this.__options = {query: {...data}};
        const systemInfo = this.SystemInfo || {};
        this.__narTop = systemInfo.CustomBar || 45;

        // // 隐藏转发按钮
        // uni.hideShareMenu && uni.hideShareMenu();
        // #ifdef MP-WEIXIN
        (async function () {
            const home_active_path = Storage.getStorageSync('home_active_path') || 0;
            const page = await vm.$util.getCurrentPageSync();
            const shareMenu = ["shareAppMessage"]
            const fIndex = vm.VERIFY_LINK.findIndex(value => {
                const paths = value.split(',');
                if (paths.length === 1 && page.route === value) return true;
                else if (page.route === paths[0] && typeof home_active_path === "number") {
                    return Number(paths[1]) === home_active_path;
                }
            })
            if (fIndex > -1) shareMenu.push("shareTimeline");
            console.log(shareMenu, "shareMenu");
            wx.showShareMenu({
                withShareTicket: true,
                menus: shareMenu
            })
        })()
        // #endif
    },
    async onShow() {
        console.warn({...arguments}, 'onShow：页面显示/切入前台时触发。');
        let that = this;
        const pages = getCurrentPages();
        const lastPage = pages[pages.length - 2];
        const currentPage = pages[pages.length - 1];
        if (lastPage) {
            const vm = lastPage.$vm || lastPage;
            vm.$$$refresh_page_id = vm._uid;
            vm.$$$isRefresh = true;
        }
        const System = that.$store.state.User
        console.log(that.$$$isRefresh, System.isOtherReturnRefresh, '判断是否需要刷新数据');
        if (that.$$$isRefresh === true) {
            console.log("回退时判断是否需要刷新数据", that.$$$isRefresh, that.$$$refresh_page_id, this._uid);
            that.$$$isRefresh = false;
            if (that.$$$refresh_page_id === this._uid) {
                that.$$$onBackPress && that.$$$onBackPress();
            }
        } else if (System.isOtherReturnRefresh === true) {
            console.log("隐藏小程序监听判断是否需要刷新数据", that.$$$isOtherReturnRefresh);
            that.$store && that.$store.commit('System/setOtherReturnRefresh', false);
            that.$$$onBackPress && that.$$$onBackPress();
        }
        that.$$$isOtherReturnRefresh = false;
    },
    onHide() {
        console.warn({...arguments}, 'onHide：页面隐藏/切入后台时触发。');
        this.$$$isRefresh = false;
    },
    onUnload(data) {
        console.warn('onUnload：页面卸载时触发。如wx.redirectTo或wx.navigateBack到其他页面时。', {...data});
    }
};

function mapKeys2(source, target) {
    Object.keys(source).forEach(key => {
        if (typeof source[key] === "function") {
            const sourceFun = source[key];
            const targetFun = typeof target[key] === 'function' ? target[key] : () => {
            };
            target[key] = function () {
                if (MERGE_DATA_EVENT_NAME.indexOf(key) > -1) {
                    const sourceData = sourceFun.call(this, ...arguments);
                    const targetData = targetFun.call(this, ...arguments);
                    const shareData = {...sourceData, ...targetData};
                    console.log(shareData, '最终数据', key);
                    return shareData
                } else {
                    const p1 = Promise.resolve(sourceFun.call(this, ...arguments));
                    const p2 = Promise.resolve(targetFun.call(this, ...arguments));
                    Promise.all([p1, p2]).then(function (opts) {
                        // console.warn(key, '调用成功', {...opts});
                    });
                }
            };
        }
    });
}

function NonValue(val) {
    switch (typeof val === "string") {
        case val === "undefined":
            val = undefined;
            break;
        case val === "null":
            val = null;
            break;
        case val === "false":
            val = false;
            break;
        case /^\d{1}$/.test(val):
            val = +val;
            break;
        default:
            val = decodeURIComponent(val);
    }
    return val
}


function AzmComponent(azmOptions = {}) {
    const common = {
        __options: {},
        __narTop: 45,
        __isShowScroll: false
    };
    const routeData = {
        length: 0,
        isRefresh: false
    };
    const scrollData = {
        isScroll: false,
        maxScroll: 200,
        scrollTop: 0
    };
    azmOptions.data = function () {
        let NavigationBarOptions = {};
        if (azmOptions.navigationBarOptions) NavigationBarOptions = azmOptions.navigationBarOptions;
        return {
            ...common,
            navigationBarOptions: {...scrollData, ...NavigationBarOptions},
            routeData,
        }
    };
    if (azmOptions.onBackPress) azmOptions.methods = {
        $$$onBackPress: azmOptions.onBackPress
    };
    delete azmOptions.onBackPress;
    // 映射生命周期函数
    mapKeys2(PAGE_LIFE_CYCLE, azmOptions);
    return deepClone1(azmOptions);
}

export {AzmComponent};
